package com.mygame.game_server.cmdHandle;

import com.mygame.game_server.User;
import com.mygame.game_server.login.LoginService;
import com.mygame.game_server.login.db.UserEntity;
import com.mygame.game_server.manager.UserManager;
import com.mygame.game_server.msg.GameMsgProtocol;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class UserLoginHandler implements ICmdHandler<GameMsgProtocol.UserLoginCmd>{
    /**
     * 日志
     */
    private static final Logger logger = LoggerFactory.getLogger(UserLoginHandler.class);

    @Override
    public void handle(ChannelHandlerContext ctx, GameMsgProtocol.UserLoginCmd cmd) {
        if (null == ctx ||
        null == cmd) {
            return;
        }

        String userName = cmd.getUserName();
        String password = cmd.getPassword();
        // 代码校验这里不会是null
/*        if (null == userName ||
        null == password) {
            return;
        }*/
        logger.info("当前运行线程 = {}" , Thread.currentThread().getName());
        //获取用户实体,利用lambda延迟执行来实现回调，即观察者模式 apply被调用时调用实现apply的逻辑
        LoginService.getInstance().userLogin(userName,password,(user -> {
            logger.info("当前运行线程 = {}" , Thread.currentThread().getName());
            GameMsgProtocol.UserLoginResult.Builder resultBuilder = GameMsgProtocol.UserLoginResult.newBuilder();

            // 登录结果
            if (null == user) {
                resultBuilder.setUserId(-1);
                resultBuilder.setUserName("")
                        .setHeroAvatar("");
            } else {
                //
                // 用户入场消息
                //
                //      GameMsgProtocol.UserEntryCmd cmd = (GameMsgProtocol.UserEntryCmd) msg;
                int userId = user.userId;
                String heroAvatar = user.heroAvatar;

                User newUser = new User();
                newUser.userId = userId;
                newUser.userName = user.userName;
                newUser.heroAvatar = heroAvatar;
                newUser.hp = 100;
                //       newUser.hp.set(100);
                UserManager.addUser(newUser);
                // 将用户id保存至session
                ctx.channel().attr(AttributeKey.valueOf("userId")).set(userId);
                resultBuilder.setUserId(user.userId)
                        .setUserName(user.userName)
                        .setHeroAvatar(user.heroAvatar);
            }

            GameMsgProtocol.UserLoginResult newResult = resultBuilder.build();
            ctx.writeAndFlush(newResult);
            return null;
        }));
//        UserEntity user = LoginService.getInstance()
//                .userLogin(cmd.getUserName(), cmd.getPassword());



    }
}
